// router/index.ts

import { createRouter, createWebHashHistory} from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import Home from '../components/Home.vue';
import profile from '../components/profile.vue';
import TodoList from '../components/TodoWeb.vue';
import TodoList_mb from '../components/TodoWeb_mb.vue';
import login from '../components/login.vue';
import { useAuthStore } from '@/store/auth'; // 导入认证存储
import Test_Results from '../components/Test_Results.vue'
import course_status from '../components/course_status.vue'
import person_status from '../components/person_status.vue'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {

        path: '/todo-list',
        name: 'TodoList',
        component: TodoList,
        meta: { requiresAuth: true } // 标记需要认证才能访问
    },
    {

        path: '/todo-list-mb',
        name: 'TodoList-mb',
        component: TodoList_mb,
        meta: { requiresAuth: true } // 标记需要认证才能访问
    },
    {
        path: '/profile',
        name: 'profile',
        component: profile
    },
    {
        path: '/login',
        name: 'login',
        component: login
    },
    {
        path: '/Test_Results',
        name: 'Test_Results',
        component: Test_Results
    },
    {
        path: '/course_status',
        name: 'course_status',
        component: course_status
    },
    {
        path: '/person_status',
        name: 'person_status',
        component: person_status
    }

];

// const router = createRouter({
//     history: createWebHistory(process.env.BASE_URL),
//     routes
// });

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 添加导航守卫
router.beforeEach((to, from, next) => {
    // 检查是否需要认证
    if (to.meta.requiresAuth) {
        // 检查用户是否已认证
        if (!useAuthStore().isAuthenticated) {
            // 如果用户未认证，重定向到登录页面，并传递当前页面路径用于登录后跳转
            next({ name: 'login', query: { redirect: to.fullPath } });
        } else {
            // 用户已认证，允许访问
            next();
        }
    } else {
        // 对于不需要认证的路由，直接允许访问
        next();
    }
});

export default router;
